package com.runing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runing.config.ResponseWrapper;
import com.runing.entity.*;
import com.runing.mapper.*;
import com.runing.service.RStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.runing.utils.ExcelUtils;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.service.ApiListing;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lel
 * @since 2021-03-11
 */
@Service
public class RStudentServiceImpl extends ServiceImpl<RStudentMapper, RStudent> implements RStudentService {

    @Autowired
    RStudentMapper studentMapper;
    @Autowired
    RCollegeMapper collegeMapper;
    @Autowired
    RClassesMapper classesMapper;
    @Autowired
    RGradeMapper gradeMapper;
    @Autowired
    RStatisticMapper statisticMapper;
    @Autowired
    RSemesterMapper semesterMapper;
    @Autowired
    RSemesterServiceImpl semesterService;
    @Autowired
    RInfoMapper infoMapper;

    @Value("${prop.upload-folder}")
    private String setPath;
    /**
     * 上传路径
     */
    private String uploadPath;
    /**
     * 返回路径
     */
    private String resPath;

    public ResponseWrapper findStudentById(Integer sid){
        if (sid == null){
            return ResponseWrapper.markCustom(false,400,"sid不能为空",null);
        }else {
            RStudent rStudent = studentMapper.selectById(sid);
            if (rStudent == null){
                return ResponseWrapper.markCustom(false,500,"没用该用户",null);
            }
            RClasses rClasses = classesMapper.selectById(rStudent.getClid());
            if (rClasses == null){
                return ResponseWrapper.markCustom(false,500,"没用该用户",null);
            }
            RCollege rCollege = collegeMapper.selectById(rClasses.getCid());
            if (rCollege == null){
                return ResponseWrapper.markCustom(false,500,"没用该用户",null);
            }
            ResponseWrapper wrapper = ResponseWrapper.markSuccess(rStudent);
            wrapper.getData().put("studentBean",rStudent);
            wrapper.getData().put("clname",rClasses.getClname());
            wrapper.getData().put("cname",rCollege.getCname());
            return wrapper;
        }
    }
    public ResponseWrapper updataStudent(RStudent rStudent){
        if (rStudent == null){
            return ResponseWrapper.markCustom(false,400,"rStudent不能为空",null);
        }else {
            RStudent student = studentMapper.selectById(rStudent.getSid());
            if (student.getSdelete() == true){
                rStudent.setSdelete(true);
                int result = studentMapper.updateById(rStudent);
                if (result == 1){
                    return ResponseWrapper.markSuccess(null);
                }else {
                    return ResponseWrapper.markError();
                }
            }else {
                int result = studentMapper.updateById(rStudent);
                if (result == 1){
                    return ResponseWrapper.markSuccess(null);
                }else {
                    return ResponseWrapper.markError();
                }
            }
        }
    }
    public ResponseWrapper updateResult(Integer sid,String inclasses,String spe){
        if (sid == null){
            return ResponseWrapper.markCustom(false,400,"请求参数为空",null);
        }else {
            RStudent student = studentMapper.selectById(sid);
            if (student == null){
                return ResponseWrapper.markCustom(false,500,"未找到该用户",null);
            }else {
                if (student.getSdelete() == true){
                    return ResponseWrapper.markCustom(false,500,"该用户已封禁无法修改",null);
                }else {
                    student.setSid(sid);
                    student.setInclass(inclasses);
                    student.setSpe(spe);
                    studentMapper.updateById(student);
                    int res = (int) (Integer.valueOf(inclasses) *0.6 + Integer.valueOf(spe) *0.2 + Integer.valueOf(student.getSrun())*0.2);
                    System.out.println("res =======>" + res);
                    QueryWrapper<RSemester> semesterQueryWrapper = new QueryWrapper<>();
                    semesterQueryWrapper.orderByDesc("seid").last("limit 1");
                    RSemester semester = semesterMapper.selectOne(semesterQueryWrapper);
                    System.out.println(semester);
                    QueryWrapper<RInfo> infoQueryWrapper = new QueryWrapper<>();
                    infoQueryWrapper.eq("sid",sid).eq("seid",semester.getSeid());
                    RInfo info = infoMapper.selectOne(infoQueryWrapper);
                    info.setSresult(String.valueOf(res));
                    int result = infoMapper.updateById(info);
                    if (result == 1){
                        return ResponseWrapper.markSuccess(null);
                    }else {
                        return ResponseWrapper.markError();
                    }

                }
            }
        }
    }

    public ResponseWrapper mobileLogin(RStudent rStudent){
        if (rStudent == null){
            return ResponseWrapper.markCustom(false,400,"rStudent不能为空",null);
        }else {
            String spassword = rStudent.getSpassword();
            QueryWrapper<RStudent> studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.eq("spassword",spassword);
            RStudent rStudents = studentMapper.selectOne(studentQueryWrapper);
            if(rStudents != null){
                if(rStudents.getSdelete() == false){
                    if (rStudent.getSname().equals(rStudents.getSname())){
                        ResponseWrapper wrapper = ResponseWrapper.markSuccess(rStudents);
                        wrapper.getData().put("data",findStudentById(rStudents.getSid()).getData());
                        return wrapper;
                    }else {
                        return ResponseWrapper.markCustom(false,500,"密码错误",null);
                    }

                }else {
                    return ResponseWrapper.markCustom(false,500,"该账号已封禁无法使用",null);
                }

            }else {
                return ResponseWrapper.markCustom(false,500,"用户名，密码错误",null);
            }

        }
    }

    public ResponseWrapper findstudentByClid(Integer clid,Integer pageSize,Integer pageNum,String sname){
        if (clid == null){
            return ResponseWrapper.markCustom(false,400,"clid不能为空",null);
        }else {
            Page<Map> page = new Page<>(pageNum,pageSize);
            IPage<Map> iPage = studentMapper.findstudentByClid(page,clid,sname);
            List<Map> list = iPage.getRecords();
            ResponseWrapper wrapper = ResponseWrapper.markSuccess(list);
            wrapper.getData().put("data",list);
            wrapper.getData().put("total",iPage.getTotal());
            wrapper.getData().put("pageSize",iPage.getSize());
            wrapper.getData().put("pageNum",iPage.getCurrent());
            return wrapper;
        }
    }
    public ResponseWrapper findStudentBySerach(Integer clid,Integer pageSize,Integer pageNum,String sname){
        Page<RStudent> page = new Page<>(pageNum,pageSize);
        QueryWrapper<RStudent> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("clid",clid).like("sname",sname);
        IPage<RStudent> students = studentMapper.selectPage(page,studentQueryWrapper);
        List list = students.getRecords();
        RClasses classes = classesMapper.selectById(clid);
        ResponseWrapper wrapper = ResponseWrapper.markSuccess(list);
        wrapper.getData().put("data",list);
        wrapper.getData().put("total",students.getTotal());
        wrapper.getData().put("pageSize",students.getSize());
        wrapper.getData().put("pageNum",students.getCurrent());
        wrapper.getData().put("clname",classes.getClname());
        return wrapper;
    }

    public ResponseWrapper picUpload(MultipartFile file) throws IOException {
        /*文件存放位置*/
        String picPath = "/picture/";
        uploadPath = setPath + picPath;
        /*返回文件路径*/
        resPath = picPath;
        /*获取文件数组*/
        ArrayList<String> list = getFile(uploadPath);
        System.out.println(file.isEmpty());
        if (file.isEmpty()) {
            return ResponseWrapper.markCustom(false,400,"上传失败",null);
        }else {
            /*获取文件名*/
            String getFileName = file.getOriginalFilename();
            BufferedImage bi = ImageIO.read(file.getInputStream());
            if (bi != null){
                String fileName = null;
                File saveFile;
                if (list.size() == 0) {
                    /*创建文件*/
                    saveFile = new File(uploadPath, getFileName);
                } else {
                    /*遍历所有文件夹，判断是否重名*/
                    fileName = checkFileName(list, getFileName,0);
                    /*创建文件*/
                    saveFile = new File(uploadPath, fileName);
                }
                if (fileName == null){
                    fileName= getFileName;
                }
                //判断文件父目录是否存在
                if (!saveFile.getParentFile().exists()) {
                    saveFile.getParentFile().mkdirs();
                    System.out.println(saveFile.getParentFile().getAbsolutePath());
                }
                try {
                    //压缩图片后保存
                    Thumbnails.of(file.getInputStream()).scale(0.5f)
                            .toFile(saveFile.getPath());
                    String url = "http://111.75.252.147:8083/Runing/picture/"+fileName;
                    ResponseWrapper wrapper = ResponseWrapper.markSuccess(url);
                    wrapper.getData().put("url",url);
                    return wrapper;
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return ResponseWrapper.markCustom(false,400,"上传失败",null);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return ResponseWrapper.markCustom(false,400,"上传失败",null);
                }
            }else {
                return ResponseWrapper.markError();
            }
        }


    }
    /**
     * @param path 需要遍历的路径
     * @return 路径下文件的名称集合
     */
    private static ArrayList<String> getFile(String path) {
        // 获得指定文件对象
        File file = new File(path);
        // 获得该文件夹内的所有文件
        File[] array = file.listFiles();
        ArrayList<String> list = new ArrayList<>();
        if (array != null) {
            for (File value : array) {
                list.add(value.getName());
            }
        }
        return list;
    }
    private static String checkFileName(ArrayList<String> names, String name, int index) {
        String indexName;
        if (index == 0 ) {
            indexName = name;
        } else {
            indexName = name.substring(0, name.indexOf(".")) + "(" + index + ")" +name.substring(name.indexOf("."));
        }
        if (names.contains(indexName)) {
            index +=1;
            name = checkFileName(names, name, index);
        } else {
            return indexName;
        }
        return name;
    }


    /**
     * @Description：导入excel并解析到数据库
     * @param file
     * @return
     */
    public ResponseWrapper UploadExcel(MultipartFile file) throws ParseException {
        if (file.isEmpty()) {
            try {
                throw new Exception("文件不存在！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        InputStream in = null;
        try {
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<List<Object>> listob = null;
        try {
            listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
            //          System.out.println("listob触发了"+listob);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //该处可调用service相应方法进行数据保存到数据库中，现只对数据输出
        for (int i = 0; i < listob.size(); i++) {
            List<Object> lo = listob.get(i);
            if (lo.size()<=2){
                return ResponseWrapper.markCustom(true,200,"导表结束",null);
            }else {
                String cname = String.valueOf(lo.get(1));
                String gname = String.valueOf(lo.get(2));
                String clname = String.valueOf(lo.get(3));
                QueryWrapper<RClasses> classesQueryWrapper = new QueryWrapper<>();
                classesQueryWrapper.eq("clname",clname);
                RClasses classes = classesMapper.selectOne(classesQueryWrapper);
                if (classes == null){
                    QueryWrapper<RCollege> collegeQueryWrapper = new QueryWrapper<>();
                    collegeQueryWrapper.eq("cname",cname);
                    RCollege college = collegeMapper.selectOne(collegeQueryWrapper);
                    if (college == null){
                        RCollege rCollege = new RCollege();
                        rCollege.setCname(cname);
                        collegeMapper.insert(rCollege);
                    }
                    RCollege colleges = collegeMapper.selectOne(collegeQueryWrapper);
                    int cid = colleges.getCid();
                    QueryWrapper<RGrade> gradeQueryWrapper = new QueryWrapper<>();
                    gradeQueryWrapper.eq("gname",gname);
                    RGrade grade = gradeMapper.selectOne(gradeQueryWrapper);
                    if (grade == null){
                        RGrade rGrade = new RGrade();
                        rGrade.setGname(gname);
                        gradeMapper.insert(rGrade);
                    }
                    RGrade grades = gradeMapper.selectOne(gradeQueryWrapper);
                    int gid =grades.getGid();
                    RClasses rClasses = new RClasses();
                    rClasses.setClname(clname);
                    rClasses.setCid(cid);
                    rClasses.setGid(gid);
                    classesMapper.insert(rClasses);
                    RClasses classe = classesMapper.selectOne(classesQueryWrapper);
                    int clid = classe.getClid();
                    RStudent rStudent = new RStudent();
                    rStudent.setSname(String.valueOf(lo.get(0)));
                    rStudent.setClid(clid);
                    rStudent.setSex(String.valueOf(lo.get(4)));
                    rStudent.setSpassword(String.valueOf(lo.get(6)));
                    rStudent.setSnum(String.valueOf(lo.get(6)));
                    System.out.println(lo.get(6));
                    System.out.println(lo.get(7));
                    rStudent.setInclass(String.valueOf(lo.get(7)));
                    rStudent.setSpe(String.valueOf(lo.get(8)));
                    studentMapper.insert(rStudent);
                }else {
                    RStudent rStudent = new RStudent();
                    int clid = classes.getClid();
                    rStudent.setSname(String.valueOf(lo.get(0)));
                    rStudent.setClid(clid);
                    rStudent.setSex(String.valueOf(lo.get(4)));
                    rStudent.setSpassword(String.valueOf(lo.get(6)));
                    rStudent.setSnum(String.valueOf(lo.get(6)));
                    rStudent.setInclass(String.valueOf(lo.get(7)));
                    rStudent.setSpe(String.valueOf(lo.get(8)));
                    QueryWrapper<RStudent> studentQueryWrapper = new QueryWrapper<>();
                    studentQueryWrapper.eq("sname",rStudent.getSname()).eq("clid",rStudent.getClid());
                    RStudent student = studentMapper.selectOne(studentQueryWrapper);
                    if (student == null){
                        studentMapper.insert(rStudent);
                        QueryWrapper<RStudent> rStudentQueryWrapper = new QueryWrapper<>();
                        rStudentQueryWrapper.eq("snum",rStudent.getSnum());
                        RStudent students = studentMapper.selectOne(rStudentQueryWrapper);
                        RInfo info = new RInfo();
                        info.setSid(students.getSid());
                        info.setSnt(0);
                        info.setSresult("0");
                        info.setAllmilsage(0);
                        info.setSeid(semesterService.findNowSemester().getSeid());
                        infoMapper.insert(info);
                    }else {
                        rStudent.setSid(student.getSid());
                        studentMapper.updateById(rStudent);
                        QueryWrapper<RInfo> infoQueryWrapper = new QueryWrapper<>();
                        infoQueryWrapper.eq("sid",student.getSid());
                        RInfo rInfo = infoMapper.selectOne(infoQueryWrapper);
                        if (rInfo == null){
                            RInfo info = new RInfo();
                            info.setSid(student.getSid());
                            info.setSnt(0);
                            info.setSresult("0");
                            info.setAllmilsage(0);
                            info.setSeid(semesterService.findNowSemester().getSeid());
                            infoMapper.insert(info);
                        }
                    }
                }

            }
        }
        return ResponseWrapper.markSuccess(null);
    }

    public void excel(HttpServletResponse response,Integer clid)throws IOException{
        //确定编码的格式
        response.setCharacterEncoding("UTF-8");
        //获取导出的数据
        QueryWrapper<RStudent> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("clid",clid);
        List<RStudent> list = studentMapper.selectList(studentQueryWrapper);
        //创建excel文件
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建sheet页
        XSSFSheet sheet = wb.createSheet("学生信息表");
        //创建标题行
        XSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("学生姓名");
        titleRow.createCell(1).setCellValue("班级");
        titleRow.createCell(2).setCellValue("性别");
        titleRow.createCell(3).setCellValue("学号");
        titleRow.createCell(4).setCellValue("课内成绩");
        titleRow.createCell(5).setCellValue("体测成绩");
        titleRow.createCell(6).setCellValue("跑步成绩");
        titleRow.createCell(7).setCellValue("总跑步次数");

        //遍历将数据放到excel列中
        for (RStudent student : list) {
            int clids = student.getClid();
            int sid = student.getSid();
            RClasses rClasses = classesMapper.selectById(clids);
            String clname = rClasses.getClname();
            QueryWrapper<RStatistic> statisticQueryWrapper = new QueryWrapper<>();
            statisticQueryWrapper.eq("sid",sid);
            int count = statisticMapper.selectCount(statisticQueryWrapper);
            System.out.println("count ==>"+count);
            XSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
            dataRow.createCell(0).setCellValue(student.getSname());
            dataRow.createCell(1).setCellValue(clname);
            dataRow.createCell(2).setCellValue(student.getSex());
            dataRow.createCell(3).setCellValue(student.getSnum());
            dataRow.createCell(4).setCellValue(student.getInclass());
            dataRow.createCell(5).setCellValue(student.getSpe());
            dataRow.createCell(6).setCellValue(student.getSrun());
            dataRow.createCell(7).setCellValue(count);
        }
            /*   // 设置下载时客户端Excel的名称
            String filename =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ".xls";
               response.setContentType("application/vnd.ms-excel");
               response.setHeader("Content-disposition", "attachment;filename=" + filename);  */

        // 设置下载时客户端Excel的名称   （上面注释的改进版本，上面的中文不支持）
        response.setContentType("application/octet-stream;charset=utf-8");
        RClasses rClasses = classesMapper.selectById(clid);
        String clname = rClasses.getClname();
        String name = clname +"跑步情况";
        response.setHeader("Content-Disposition", "attachment;filename="
                //该版本为2007-的版本
                + new String(name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)
                + ".xlsx");
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();

    }

    public ResponseWrapper findBadStudent(Integer pageSize,Integer pageNum){
        Page<Map> page = new Page<>(pageNum,pageSize);
        IPage<Map> iPage = studentMapper.findBadStudent(page);
        List<Map> list = iPage.getRecords();
        ResponseWrapper wrapper = ResponseWrapper.markSuccess(list);
        wrapper.getData().put("data",list);
        wrapper.getData().put("total",iPage.getTotal());
        wrapper.getData().put("pageSize",iPage.getSize());
        wrapper.getData().put("pageNum",iPage.getCurrent());
        return wrapper;

    }

}
